#! /usr/bin/tclsh

# Script logging location

set homeDir /Users/reverend
set appDir EncodeForDvd
set logDir $homeDir/logs/$appDir

set now [clock seconds]
set year [clock format $now -format %Y]
set month [clock format $now -format %m]
set day [clock format $now -format %d]

set logDir $logDir/$year/$month/$day
set logFile app.log
set outputFile app.out

file mkdir $logDir

proc log {msg} {
    set f [open $::logDir/$::logFile a]
    puts $f "[clock format [clock seconds]] : $msg"
    close $f
}

log "==== encodeForDvd starting ===="

# Message file, indicating a directory of files has been encoded
set alreadyEncodedFileName encoded

# Message file, indicating a directory of files should be encoded
set encodeFileName encode

proc shouldEncode {checkDir} {
    return [expr {![file exists $checkDir/$::alreadyEncodedFileName] && [file exists $checkDir/$::encodeFileName]}]
}

# Work directory

set rootDir /Volumes/GREMLIN/Porn/mip

if {![file exists $rootDir]} {
    log "Work directory does not exist... exiting"
    exit -1
}

proc encodeFiles {inDir} {
    log "Starting to encode files in $inDir"
    set wmvFiles [glob $inDir/*.wmv]
    foreach wmvFile $wmvFiles {
        set stripped [lindex [split $wmvFile {.}] 0]
        set stripList [split $stripped {/}]
        set lastIndex [expr {[llength $stripList] - 1}]
        set toEncode [lindex $stripList $lastIndex]
        set encodeDir [join [lrange $stripList 0 [expr $lastIndex -1]] {/}]
       # puts "$encodeDir/$toEncode.wmv : [file exists $encodeDir/$toEncode.wmv]"

        set encodeToDir $encodeDir/mpg
        file mkdir $encodeToDir
        log "Encoding ${toEncode}.wmv"
        catch {
            exec ffmpeg -i ${encodeDir}/${toEncode}.wmv -pass 1 -target ntsc-dvd -aspect 16:9 ${encodeToDir}/${toEncode}.mpg
        } result
        catch {
            exec ffmpeg -i ${encodeDir}/${toEncode}.wmv -y -pass 2 -target ntsc-dvd -aspect 16:9 ${encodeToDir}/${toEncode}.mpg
        } result
    }
    file delete $inDir/$::encodeFileName
    set f [open $inDir/$::alreadyEncodedFileName w]
    puts $f [clock format [clock seconds]]
    close $f
}

set dirList [glob $rootDir/* -type d]

foreach dir $dirList {
    if {[shouldEncode $dir]} {
        encodeFiles $dir
    } else {
        continue
    }
}




log "==== encodeForDvd finished ===="
exit 0
